package org.meb.speedway.log;

public class LogBuilder {

	private StringBuilder itemBuilder;
	private StringBuilder detailBuilder;
	private Log log;
	private LogItem item;

	public LogBuilder() {
		itemBuilder = new StringBuilder();
		detailBuilder = new StringBuilder();
	}

	private StringBuilder getOrCreateItemBuilder() {
		if (itemBuilder == null) {
			itemBuilder = new StringBuilder();
		}
		return itemBuilder;
	}

	private StringBuilder getOrCreateDetailBuilder() {
		if (detailBuilder == null) {
			detailBuilder = new StringBuilder();
		}
		return detailBuilder;
	}

	private void lazyInit() {
		if (log == null && item == null) {
			log = new Log();
			item = new LogItem();
		}
	}

	// private void commitItem() {
	// if (itemBuilder != null) {
	// item.setMessage(itemBuilder.toString());
	// }
	// itemBuilder = null;
	// commitDetail();
	// log.getItems().add(item);
	// item = new LogItem();
	// }
	//
	// private void commitDetail() {
	// if (detailBuilder != null) {
	// item.getDetails().add(detailBuilder.toString());
	// }
	// detailBuilder = null;
	// }

	public LogBuilder item(String text) {
		lazyInit();
		getOrCreateItemBuilder().append(text);
		return this;
	}

	public LogBuilder nextItem(String text) {
		lazyInit();
		// commitItem();
		getOrCreateItemBuilder().append(text);
		return this;
	}

	public LogBuilder detail(String text) {
		lazyInit();
		getOrCreateDetailBuilder().append(text);
		return this;
	}

	public LogBuilder nextDetail(String text) {
		lazyInit();
		if (detailBuilder != null) {
			item.getDetails().add(detailBuilder.toString());
		}
		detailBuilder = null;
		detailBuilder.append(text);
		return this;
	}

	public Log build() {
		item.setMessage(itemBuilder.toString());
		if (detailBuilder.toString() != null) {
			item.getDetails().add(detailBuilder.toString());
		}
		log.getItems().add(item);
		Log tmp = log;
		log = null;
		item = null;
		return tmp;
	}
}
